package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Employee;
import com.itheima.service.EmployeeService;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/employee")
@Api(tags = "员工管理相关接口")
public class EmployeeController {


    @Autowired
    private EmployeeService employeeService;


    @GetMapping("/{id}")
    public R getById(@PathVariable Long id){
        Employee byId = employeeService.getById(id);
        return R.success(byId);
    }

    @PutMapping
    public R<String> updateEmployee(@RequestBody Employee employee){

        employeeService.updateById(employee);//update xxx set status =? where id=?

        return R.success("修改成功");
    }



    @GetMapping("/page")
    public R<IPage<Employee>> pageQueryEmployee(Integer page,
                               Integer pageSize,
                               String name){
        //分页参数封装  new Page<Employee>(当前页，每页大小)
        IPage<Employee> pageCondition =
                new Page<Employee>(page,pageSize);
        //封装查询条件 new LambdaQueryWrapper() : where name like '%xxx%'
        // like(条件,xx,xx)
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Employee::getName,name);

        //添加默认排序 orderByDesc() :  order by update_time desc
        qw.orderByDesc(Employee::getUpdateTime);

        employeeService.page(pageCondition,qw);
        long total = pageCondition.getTotal();//total
        List<Employee> records = pageCondition.getRecords();//records
        return R.success(pageCondition);
    }


    @PostMapping
    public R<String> addEmployee(@RequestBody Employee employee){
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(1);
        employeeService.save(employee);
        return R.success("添加员工成功，初始密码是：123456");
    }

    @PostMapping("/login")
    // springmvc 提供了获取servlet相关对象的便捷方式 方法形参！！
    public R<Employee> login(HttpSession session,
                             @RequestBody Employee employee){
        //1、获取用户名+密码 ：Employee对象接收数据
        //2、根据用户名查询用户信息：  select * from user where username=?
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(qw);
        //判断：查询不到，返回登录失败
        if(emp == null){
            return R.error("用户不存在");
        }
        //3、如果查询到了，比对密码是否正确【用户输入的密码加密后 和 数据库的密码进行比对】
        //3.1、用户输入的密码加密
        String passwordMD5 = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        //判断： 比对失败，返回登录失败
        if(!emp.getPassword().equals(passwordMD5)){
            return R.error("密码错误");
        }
        //4、比对成功，说明用户名和密码是对的。
        // 判断：用户是否禁用【status：0禁用  1正常】，如果是禁用，返回登录失败【员工已禁用】
        if(emp.getStatus()==0){
            return R.error("用户被禁用，不允许登录");
        }
        //5、用户状态正常。登录成功。
        // 5.1、存用户信息【只存用户的id】到session。
        session.setAttribute("employee",emp.getId());
        //5.2、返回响应结果
        return R.success(emp);
    }


    @PostMapping("/logout")
    public R logout(HttpSession httpSession){
        httpSession.invalidate();
        return R.success("退出成功");
    }
}
